package com.wthink.card.models;

import java.nio.ByteBuffer;


public class TcpClientFrameBundle {

	public int frameBundleState;
	public int frameBundleBodyCurrLen = 0;

	public int useExternalBuffer = 0; // save frame body to external buffer

	public int frameBundleSubType = 0;
	public int frameBundleMainType = 0;
	public int frameBundleBodyLen = 0;
	public int frameBundleChkSum = 0;
	public byte[] frameBundleBody;
	
	// frame state for parser
	public static final int FS_NOT_READY = 0; // FRAME body wasn't fullfilled
	public static final int FS_BODY_READY = 1; // frame body is fullfilled ,
												// it's ready for process
	public static final int FS_FRM_READY = 2;
	public static final int FS_PROCESSED = 3; // This msg is processed..

	public TcpClientFrameBundle() {
		frameBundleState = 0;
	}


	public int getFrameBundleState() {
		return frameBundleState;
	}

	public void setFrameBundleState(int state) {
		frameBundleState = state;
	}



	public void setFrameBundleBodyLen(int len) {
		frameBundleBodyLen = len;
	}

	public byte[] getFrameBundleBody() {
		return frameBundleBody;
	}



	public void prepareFrameBundleBody() {
		if (frameBundleBody == null && (useExternalBuffer == 0)) {
			frameBundleBody = new byte[frameBundleBodyLen - 2];
		}
	}

	public int fillFrameBundleBody(ByteBuffer src, int maxdatalen) {
		
		byte[] tail = new byte[2]; 
		int bodyDemandLen = frameBundleBodyLen - frameBundleBodyCurrLen;
		if (maxdatalen >= bodyDemandLen) {
			src.get(frameBundleBody, frameBundleBodyCurrLen, bodyDemandLen-2);
			src.get(tail); 
			frameBundleBodyCurrLen += bodyDemandLen;
			return 0;  // read body ok!!
		} else {//maxdatalen < bodyDemandLen
			if (maxdatalen <= bodyDemandLen-2) {
				try{
					src.get(frameBundleBody, frameBundleBodyCurrLen, maxdatalen);
					frameBundleBodyCurrLen += maxdatalen;
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			return -1;  // we want more...
		}
	}
}
